import * as fs from 'fs';
import * as path from 'path';
import { randomBytes } from 'crypto';
import { Jimp } from 'jimp';
import * as http from 'http';
import * as https from 'https';
const ROOT_PATH = path.join(__dirname, '../../');

export function LoadPrompt(name: string) {
  const p = path.join(__dirname, `../prompts/${name}.md`);
  const buf = fs.readFileSync(p, 'utf8');
  return buf.toString();
}

export function SaveToFile(p: string, content: string) {
  if (content.startsWith('```markdown')) {
    content = content.replace('```markdown', '');
    content = content.replace('```', '');
  }
  const filePath = path.join(ROOT_PATH, p);
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  fs.writeFileSync(filePath, content, { flag: 'w+' });
}

export function SaveToLog(content: string, append: boolean = true) {
  const p = 'aiop.log';
  const dir = path.dirname(p);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true }); // 自动创建目录
  }
  append ? fs.appendFileSync(p, content) : fs.writeFileSync(p, content);
}

export function GenID(len = 4) {
  return randomBytes(len).toString('hex');
}

export function LoadFile(pathOrKey: string) {
  try {
    return fs.readFileSync(pathOrKey, 'utf8').toString();
  } catch (error) {
    return "";
  }
}

export function LoadDir(pathOrKey: string) {
  return fs.readdirSync(pathOrKey);
}

export function logToFile(content: string) {
  if (process.env.NODE_ENV == "dev") {
    const timestamp = new Date()
    const options = {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false // 使用24小时制
    };
    const timeStr = timestamp.toLocaleString('zh-CN', options as any);
    const logEntry = `[${timeStr}] ${content}\n`;
    fs.appendFileSync('debug_log.log', logEntry);
  }
}

export async function imageToBase64(imagePath: string) {
  try {
    // 检查文件是否存在
    if (!fs.existsSync(imagePath)) {
      return "";
    }

    // 读取文件并转换为 base64
    const image = await Jimp.read(imagePath);

    // 3. 等比例缩放
    // image.resize({ w: newWidth, h: newHeight });
    const jpegImageBuffer = await image.getBuffer("image/jpeg");
    const base64String = jpegImageBuffer.toString('base64');

    // 返回完整的 data URL
    return `data:image/jpeg;base64,${base64String}`;
  } catch (error) {
    throw new Error(`Failed to read image file: ${error.message}`);
  }
}

export async function imageUrlToBase64(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const client = url.startsWith('https') ? https : http;

    client.get(url, (response) => {
      if (response.statusCode !== 200) {
        reject(new Error(`Failed to fetch image: ${response.statusCode} ${response.statusMessage}`));
        return;
      }

      const chunks: Buffer[] = [];

      response.on('data', (chunk: Buffer) => {
        chunks.push(chunk);
      });

      response.on('end', () => {
        const buffer = Buffer.concat(chunks);
        const base64String = buffer.toString('base64');

        // 根据Content-Type确定MIME类型，如果没有则默认为jpeg
        const contentType = response.headers['content-type'] || 'image/jpeg';
        resolve(`data:${contentType};base64,${base64String}`);
      });
    }).on('error', (error) => {
      reject(new Error(`Failed to fetch image: ${error.message}`));
    });
  });
}

export async function downloadImage(url: string, savePath?: string): Promise<string> {
  const filename = GenID();
  try {
    // 如果没有提供保存路径，则生成一个默认路径
    if (!savePath) {
      let defaultDir = path.join(__dirname, '../../uploads');
      if (process.env.USER_DIR) { 
        defaultDir = path.join(process.env.USER_DIR, 'uploads');
      }
      savePath = path.join(defaultDir, filename);
    }

    // 确保保存路径的目录存在
    const dir = path.dirname(savePath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    // 使用Jimp直接从URL读取图片
    const image = await Jimp.read(url);

    // 转换为JPEG格式并保存
    await image.write(`${savePath}.jpg`);

    return filename + ".jpg";
  } catch (error) {
    console.error('Error saving image:', error);
  }
}

export function formatDuration(milliseconds: number): string {
  if (milliseconds < 1000) {
    return `${milliseconds}ms`;
  } else if (milliseconds < 60000) {
    return `${(milliseconds / 1000).toFixed(2)}s`;
  } else if (milliseconds < 3600000) {
    return `${(milliseconds / 60000).toFixed(2)}min`;
  } else {
    return `${(milliseconds / 3600000).toFixed(2)}h`;
  }
}